<template>
  <div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="800px" @close="resetForm('addForm')">
      <el-form :model="form" status-icon :rules="rules" ref="addForm">
        <el-form-item label="商品标题" prop="name" :label-width="labelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品单价" prop="price" :label-width="labelWidth">
          <el-input-number v-model="form.price" :step="1" :min="0" controls-position="right">
          </el-input-number> （人民币/元）
        </el-form-item>
        <el-form-item label="公蟹" prop="specs_male" :label-width="labelWidth">
          <el-input-number v-model="form.specs_male[0]" :precision="1" :step="1" :min="1" controls-position="right"
            style="width: 150px;">
          </el-input-number> （重量/两）
          <el-input-number v-model="form.specs_male[1]" :step="1" :min="1" controls-position="right"
            style="width: 120px; margin-left: 20px;">
          </el-input-number> （数量/只）
          </el-input>
        </el-form-item>
        <el-form-item label="母蟹" prop="specs_female" :label-width="labelWidth">
          <el-input-number v-model="form.specs_female[0]" :precision="1" :step="1" :min="1" controls-position="right"
            style="width: 150px;">
          </el-input-number> （重量/两）
          <el-input-number v-model="form.specs_female[1]" :step="1" :min="1" controls-position="right"
            style="width: 120px; margin-left: 20px;">
          </el-input-number> （数量/只）
          </el-input>
        </el-form-item>
        <el-form-item label="主图" prop="mainPic" :label-width="labelWidth">
          <el-upload class="upload-main" list-type="picture" ref="uploadMain" :limit="1" :action="uploadApi"
            :on-remove="(file, fileList) => onUploadRemove(file, fileList, 'main')" :file-list="mainPicList"
            :on-success="(res, file, fileList) => onUploadSuccess(res, file, fileList, 'main')"
            :on-preview="handlePictureCardPreview" :on-error="onUploadError" accept=".jpg, .png"
            :before-upload="onUploadBefore" :auto-upload="true">
            <el-button size="small" type="primary"
              :disabled="mainPicList.length === 1">{{mainPicList.length === 1 ? "仅限一张" : "选择图片"}}</el-button>
            <div slot="tip" class="el-upload__tip">只能上传 1 张 500K 以下的 jpg或png 文件。</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图" prop="detailPic" :label-width="labelWidth">
          <el-upload class="upload-detail" list-type="picture" ref="uploadDetail" :action="uploadApi"
            :on-remove="(file, fileList) => onUploadRemove(file, fileList, 'detail')" :file-list="detailPicList"
            :on-success="(res, file, fileList) => onUploadSuccess(res, file, fileList, 'detail')"
            :on-error="onUploadError" accept=".jpg, .png" :on-preview="handlePictureCardPreview"
            :before-upload="onUploadBefore" :auto-upload="true">
            <el-button size="small" type="primary">选择图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传 500K 以下的 jpg或png 文件。</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog append-to-body close-on-click-modal class="privewDialog" :visible.sync="previewDialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import {
    saveGoods
  } from "@/api/goods"
  export default {
    data() {
      let checkNumber = (rule, value, callback) => {
        if (value === 0) {
          callback(new Error('请输入正确数字'));
        } else if (!/^-?\d+(\.\d+)?$/.test(value)) {
          callback(new Error('请输入有效的数字'));
        } else {
          callback();
        }
      }
      let checkSpecs = (rule, value, callback) => {
        const specs = value || [];
        if (specs.some(item => item === undefined)) {
          callback(new Error('请在该行两个输入框均输入正确数字'));
        } else {
          callback();
        }
      }
      return {
        uploadApi: process.env.VUE_APP_BASE_API + "/api/uploads",
        imgPrefix: process.env.VUE_APP_BASE_API + '/api/',
        dialogFormVisible: false,
        labelWidth: "100px",
        dialogTitle: "",
        form: {
          name: "",
          specs_male: [undefined, undefined],
          specs_female: [undefined, undefined],
          price: null,
          rule: "",
          detailPic: [],
          mainPic: []
        },
        mainPicList: [],
        detailPicList: [],
        successfulUploads: 0,
        totalFiles: 0,
        dialogImageUrl: '',
        previewDialogVisible: false,
        rules: {
          name: [{
            required: true,
            message: '商品标题不能为空',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '单价不能为空',
            validator: checkNumber,
            trigger: 'blur'
          }],
          score: [{
            required: true,
            validator: checkNumber,
            trigger: 'blur'
          }],
          specs_male: [{
            required: true,
            validator: checkSpecs,
            trigger: ['blur']
          }],
          specs_female: [{
            required: true,
            validator: checkSpecs,
            trigger: ['blur']
          }]
        }
      }
    },
    mounted() {
      this.$bus.$on("addGoodsBtnClick", () => {
        this.dialogTitle = "新增商品";
        this.addInit()
      });
      this.$bus.$on("onEditDetails", (data) => {
        this.dialogTitle = "修改商品信息";
        this.editInit(data)
      })
    },
    beforeDestroy() {
      this.$bus.$off("addGoodsBtnClick");
      this.$bus.$off("editGoodsBtnClick")
    },
    methods: {
      addInit() {
        this.dialogFormVisible = true;
        this.form = {
          name: "",
          specs_male: [undefined, undefined],
          specs_female: [undefined, undefined],
          price: null,
          detailPic: [],
          mainPic: []
        }
      },
      editInit(data) {
        this.form = data
        this.mainPicList = [{
          name: data.mainPic,
          url: this.imgPrefix + data.mainPic
        }];
        this.detailPicList = data.detailPic.map(item => {
          return item = {
            name: item,
            url: this.imgPrefix + item
          }
        });
        // console.log(this.detailPicList)
        this.dialogFormVisible = true;
      },
      async submitForm(formName) {
        try {
          // console.log(this.form)
          if (!this.form.mainPic.length || !this.form.detailPic.length) {
            this.$message.error('主图或详情图还没传！')
            return
          }
          const valid = await this.$refs[formName].validate();
          if (valid) {
            let res = await saveGoods(this.form);
            this.dialogFormVisible = false;
            this.$message({
              message: "操作成功！",
              type: "success"
            });
            this.$bus.$emit("onSaveGoods");
            this.resetForm(formName)
          } else {
            console.log(this.form);
            return false;
          }
        } catch (e) {
          //TODO handle the exception
          console.log("error", e)
        }
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
        this.$refs['uploadMain'].clearFiles()
        this.$refs['uploadDetail'].clearFiles()
        this.mainPicList.length = 0; //初始化为了防止下次打开dialog上传主图按钮还是disabled状态
        this.detailPicList.length = 0;
      },

      // beforeUpload
      onUploadBefore(file) {
        // console.log(file)
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt500K = file.size / 1024 / 1024 < 0.5;
        if (!isJPG) {
          this.$message.error('只能是 JPG 或 PNG 格式!');
        }
        if (!isLt500K) {
          this.$message.error('大小不能超过 500K!');
        }
        this.picValidated = isJPG && isLt500K
        return isJPG && isLt500K;
      },
      // 上传处理
      onUploadSuccess(res, file, fileList, flag) {
        let picList, formPic;
        if (flag === "main") {
          picList = this.mainPicList
          formPic = this.form.mainPic
        } else {
          picList = this.detailPicList
          formPic = this.form.detailPic
        }
        // 如果失败，报错，删除错误的那个
        if (res.status !== 200) {
          // console.log(res, 'eee')
          this.$message({
            message: res.message || 'Error',
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          // console.log(res, 'dddddddddddd')
          this.$message.success('上传成功！');
          if (flag === "main") {
            this.mainPicList = fileList;
            this.form.mainPic.push(file.response.data.url)
          } else {
            this.detailPicList = fileList;
            this.form.detailPic.push(file.response.data.url)
          }
        }
      },
      //移除图片
      onUploadRemove(file, fileList, flag) {
        // console.log(file, fileList)
        if (flag === 'main') {
          this.mainPicList = [];
          this.form.mainPic = [];
        } else {
          this.detailPicList = fileList;
          this.form.detailPic = fileList.map(item => {
            if (typeof(item) !== "string") {
              if(item.url.indexOf('blob:') > -1){
                return item.response.data.url
              }else{
                return item.url.replace(this.imgPrefix, '')
              }
            } else {
              return item
            }
          })
        }

      },
      // 图片预览
      handlePictureCardPreview(file) {
        // console.log(file)
        this.dialogImageUrl = file.url;
        this.previewDialogVisible = true;
      },
      onUploadError(err, file, fileList) {
        if (err) {
          this.$message.error(`文件上传失败: ${err.message}`);
        }
      },
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .el-dialog__body {
    max-height: 70vh;
    overflow-y: scroll;
  }

  ::v-deep .el-upload-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  ::v-deep .el-form-item__content {
    line-height: 16px !important;

    .el-upload__tip {
      color: #999;
    }
  }


  ::v-deep .el-upload--picture-card,
  ::v-deep .el-upload-list__item {
    width: 49% !important;
    line-height: 118px;
  }

  ::v-deep .el-upload-list__item.is-success.focusing .el-icon-close-tip {
    display: none !important;
  }
</style>
